package com.wenli.lt.util;



import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.wenli.lt.config.GlobalParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 阿里云 OSS文件类
 *
 * @author zouyuan
 */
@Component
public class OSSClientUtil {

    Logger log = LoggerFactory.getLogger(OSSClientUtil.class);

    GlobalParam globalParam ;

    @Autowired
    OSSClientUtil(GlobalParam globalParam){
        this.globalParam  =globalParam;
    }



    /**
     * 上传图片
     *
     * @param url
     */
    public void uploadImg2Oss(String url) throws IOException {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new IOException("图片上传失败");
        }
    }


    public String uploadImg2Oss(MultipartFile file) throws IOException {
        if (file.getSize() > 20*1024 * 1024) {
            throw new IOException("上传图片大小不能超过20M！");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        } catch (Exception e) {
            throw new IOException("图片上传失败");
        }
    }

    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(globalParam.getFileDir()+ split[split.length - 1]);
        }
        return null;
    }

    public boolean deleteObject( List<String> bucketUrls) {
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        // 私有云要关闭CNAME
        conf.setSupportCname(false);
        OSS ossClient = new OSSClientBuilder().build(globalParam.getEndpoint(),globalParam.getAccessKeyId(), globalParam.getAccessKeySecret(),conf);
        try {
            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(globalParam.getBucketName()).withKeys(bucketUrls));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            log.info("deletedObjects"+ deletedObjects);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ossClient.shutdown();
        }
        return true;
    }




    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        // 私有云要关闭CNAME
        conf.setSupportCname(false);
        OSS ossClient = new OSSClientBuilder().build(globalParam.getEndpoint(),globalParam.getAccessKeyId(), globalParam.getAccessKeySecret(),conf);        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            log.info(globalParam.getFileDir());
            log.info(globalParam.getBucketName());
            PutObjectResult putObjectResult = ossClient.putObject(globalParam.getBucketName(), globalParam.getFileDir() + fileName, instream, objectMetadata);
            ret = putObjectResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            ossClient.shutdown();
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }



    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
//            return "image/jpeg";
            //预览  jpg //下载  jpeg
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
//        return "image/jpeg";
        return "image/jpg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        // 私有云要关闭CNAME
        conf.setSupportCname(false);
        OSS ossClient = new OSSClientBuilder().build(globalParam.getEndpoint(),globalParam.getAccessKeyId(), globalParam.getAccessKeySecret(),conf);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        GeneratePresignedUrlRequest generatePresignedUrlRequest ;
        generatePresignedUrlRequest =new GeneratePresignedUrlRequest(globalParam.getBucketName(), key);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
       // URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        ossClient.shutdown();
        return null;
    }

    /**
     * 根据oss路径获取Base64位码
     * @param picName
     * @return
     * @throws IOException
     */
    public String getBase64ByName(String picName) throws IOException {
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        // 私有云要关闭CNAME
        conf.setSupportCname(false);
        OSS ossClient = new OSSClientBuilder().build(globalParam.getEndpoint(),globalParam.getAccessKeyId(), globalParam.getAccessKeySecret(),conf);
//        // 构造ListObjectsRequest请求
//        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
//        // List Objects
//        ObjectListing listing = ossClient.listObjects(listObjectsRequest);
//        // 遍历所有Object
//        System.out.println("Objects:");
//        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
//            System.out.println(objectSummary.getKey());
//        }
        OSSObject object = ossClient.getObject(globalParam.getBucketName(), globalParam.getFileDir()+picName);
        BufferedInputStream input = new BufferedInputStream(object.getObjectContent());
        ossClient.shutdown();
        return getWxQrCodeStr(input);
    }

    /**
     * BufferedInputStream 转base64位码
     * @param wxQrCode
     * @return
     * @throws IOException
     */
    public String getWxQrCodeStr(BufferedInputStream wxQrCode) throws IOException {
        String encode = null;
        if (wxQrCode != null) {
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len;
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            while ((len = wxQrCode.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            wxQrCode.close();
            byte[] bytes = outStream.toByteArray();
//      wxQrCode.read(bytes);
            BASE64Encoder base64Encoder = new BASE64Encoder();
            encode = base64Encoder.encode(bytes);
        }
        return encode;
    }
}
